package shc.graduation.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.shey.refreshlayout.RefreshLayout;
import com.shey.refreshlayout.SwipeRefreshLayout;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import shc.graduation.R;
import shc.graduation.adapter.GroupAdapter;
import shc.graduation.adapter.ModelInfoAdapter;
import shc.graduation.bean.CodeGroup;
import shc.graduation.bean.CodeInfo;
import shc.graduation.bean.MyCollection;
import shc.graduation.bean.PaoWangArticle;
import shc.graduation.bean.PaoWangGroup;
import shc.graduation.bean.PaperGroup;
import shc.graduation.bean.PaperInfo;
import shc.graduation.bean.StateEvent;
import shc.graduation.http.listener.QueryListener;
import shc.graduation.http.listener.TaskListener;
import shc.graduation.http.manager.QueryManager;
import shc.graduation.http.manager.TaskManager;
import shc.graduation.http.task.ITask;
import shc.graduation.http.task.TaskOption;
import shc.graduation.utils.ServerUtil;
import shc.graduation.view.FloatingActionButton;


public class MainActivity extends BaseActivity {

    private RefreshLayout mRefreshLayout;
    private ListView mMainListView;
    private ListView mRightListView;
    private DrawerLayout mDrawerLayout;
    private NavigationView mNavigationView;
    private FloatingActionButton floatingActionButton;
    //上一次按返回键的时间
    private static long mLastBackTime = 0;

    private ModelInfoAdapter mModelInfoAdapter = null;
    private GroupAdapter mGroupAdapter = null;

    private TaskManager mTaskManager = null;
    private QueryManager mQueryManager = null;

    /**
     * 为了分组 没办法
     **/
    private List<DataSupport> codeInfoDataSupport = null;
    private List<DataSupport> paoWangDataSupport = null;
    private List<DataSupport> paperDataSupport = null;

    private static int Project_id = 0;
    private static final int OPEN_CODE = 0;
    private static final int PAOWANG_ARTICLE = 1;
    private static final int PAPER_ARTICLE = 2;
    private static final int MYCOLLECTION = 3;

    private static int Group_id = 1;
    private static int Page_index = 1;
    private static int actionType = 0;

    private static String PROJECT_ID = "project_id";
    private static String GROUP_ID = "group_id";
    private static String PAGE_INDEX = "page_index";

    private static String Group_url = null;
    private static String Code_Group_Url = null;
    private static String PaoWang_Group_Url = null;
    private static String Paper_Group_Url = null;

    private MaterialDialog mMaterialDialog = null;

    private PowerManager.WakeLock wakeLock = null;

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            mNavigationView.setVisibility(View.VISIBLE);
            mMaterialDialog.dismiss();
        }
    };

    private TaskListener modelInfoListener = new TaskListener() {
        @Override
        public void running(ITask iTask, String runningInfo) {

        }

        @Override
        public void success(ITask iTask, String successInfo) {
            if (wakeLock != null) {
                wakeLock.release();
                wakeLock = null;
            }

            executeQuery();
        }

        @Override
        public void fail(ITask iTask, String failInfo) {
            if (wakeLock != null) {
                wakeLock.release();
                wakeLock = null;
            }

            refreshLayout(false);
        }
    };

    @Override
    public void onCreate(Bundle saveInsatanceState, View decorView) {
        enabledHomeButton();

        mModelInfoAdapter = new ModelInfoAdapter(mContext, null);
        mMainListView.setAdapter(mModelInfoAdapter);

        mGroupAdapter = new GroupAdapter(mContext, null);
        mRightListView.setAdapter(mGroupAdapter);


        mTaskManager = TaskManager.getInstance();
        mQueryManager = QueryManager.getInstance();

        initNavigationView();

        initRefreshLayout();

        initListView();

        mMaterialDialog = new MaterialDialog.Builder(mContext)
                .content("正在更新数据库分组内容")
                .cancelable(false)
                .progress(true, 0)
                .progressIndeterminateStyle(true)
                .show();

        initGroupList();

    }

    private void initGroupList() {
        new Thread() {
            @Override
            public void run() {

                List<CodeGroup> codeGroupList = DataSupport.findAll(CodeGroup.class);
                List<PaoWangGroup> paoWangGroupList = DataSupport.findAll(PaoWangGroup.class);
                List<PaperGroup> paperGroupList = DataSupport.findAll(PaperGroup.class);

                if (codeGroupList != null && codeGroupList.size() > 0) {
                    Code_Group_Url = codeGroupList.get(0).getGroupUrl();
                }
                if (paoWangGroupList != null && paoWangGroupList.size() > 0) {
                    PaoWang_Group_Url = paoWangGroupList.get(0).getGroupUrl();
                }
                if (paperGroupList != null && paperGroupList.size() > 0) {
                    Paper_Group_Url = paperGroupList.get(0).getGroupUrl();
                }

                codeInfoDataSupport = new ArrayList<>(codeGroupList.size());
                for (CodeGroup codeGroup : codeGroupList) {
                    codeInfoDataSupport.add(codeGroup);
                }

                paoWangDataSupport = new ArrayList<>(paoWangGroupList.size());
                for (PaoWangGroup paoWangGroup : paoWangGroupList) {
                    paoWangDataSupport.add(paoWangGroup);
                }

                paperDataSupport = new ArrayList<>(paperGroupList.size());
                for (PaperGroup paperGroup : paperGroupList) {
                    paperDataSupport.add(paperGroup);
                }

                codeGroupList.clear();
                codeGroupList = null;

                paoWangGroupList.clear();
                paoWangGroupList = null;

                paperGroupList.clear();
                paperGroupList = null;

                mHandler.sendEmptyMessage(0);
            }

        }.start();

    }

    private void initListView() {
        setMainListViewItemClickListener();

        //        setMainListViewItemLongClickListener();

        setRightListViewItemClickListener();

    }

    private void setRightListViewItemClickListener() {
        mRightListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mGroupAdapter.setSelectIndex(position);

                switch (Project_id) {
                    case OPEN_CODE:

                        CodeGroup codeGroup = (CodeGroup) mGroupAdapter.getItem(position);
                        Group_id = codeGroup.getId();
                        Group_url = codeGroup.getGroupUrl();
                        break;

                    case PAOWANG_ARTICLE:

                        PaoWangGroup paoWangGroup = (PaoWangGroup) mGroupAdapter.getItem(position);
                        Group_id = paoWangGroup.getId();
                        Group_url = paoWangGroup.getGroupUrl();
                        break;

                    case PAPER_ARTICLE:

                        PaperGroup paperGroup = (PaperGroup) mGroupAdapter.getItem(position);
                        Group_id = paperGroup.getId();
                        Group_url = paperGroup.getGroupUrl();
                        break;
                }
                mDrawerLayout.closeDrawer(GravityCompat.END);
                mModelInfoAdapter.removeAll();
                executeQuery();
            }

        });
    }

    private void setMainListViewItemLongClickListener() {
        mMainListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                switch (Project_id) {
                    case OPEN_CODE:

                        final CodeInfo codeInfo2 = (CodeInfo) mModelInfoAdapter.getItem(position);

                        if (TextUtils.isEmpty(codeInfo2.getGithubUrl())) {
                            return true;
                        }

                        new MaterialDialog.Builder(mContext)
                                .content(R.string.ifshare_github_address)
                                .positiveText(R.string.sure)
                                .negativeText(R.string.cancel)
                                .backgroundColor(mContext.getResources().getColor(R.color.white))
                                .contentColor(mContext.getResources().getColor(R.color.black))
                                .callback(new MaterialDialog.ButtonCallback() {
                                    @Override
                                    public void onPositive(MaterialDialog dialog) {
                                        Intent sendIntent = new Intent();
                                        sendIntent.setAction(Intent.ACTION_SEND);
                                        sendIntent.putExtra(Intent.EXTRA_TEXT, codeInfo2.getGithubUrl());
                                        sendIntent.setType("text/plain");
                                        startActivity(sendIntent);

                                        dialog.dismiss();
                                    }

                                    @Override
                                    public void onNegative(MaterialDialog dialog) {
                                        dialog.dismiss();
                                    }
                                })
                                .build()
                                .show();

                        break;

                    case PAOWANG_ARTICLE:

                        final PaoWangArticle paowang = (PaoWangArticle) mModelInfoAdapter.getItem(position);

                        if (TextUtils.isEmpty(paowang.getContentUrl())) {
                            return true;
                        }

                        new MaterialDialog.Builder(mContext)
                                .content(R.string.ifshare_content_address)
                                .positiveText(R.string.sure)
                                .negativeText(R.string.cancel)
                                .backgroundColor(mContext.getResources().getColor(R.color.white))
                                .contentColor(mContext.getResources().getColor(R.color.black))
                                .callback(new MaterialDialog.ButtonCallback() {
                                    @Override
                                    public void onPositive(MaterialDialog dialog) {

                                        Intent sendIntent = new Intent();
                                        sendIntent.setAction(Intent.ACTION_SEND);
                                        sendIntent.putExtra(Intent.EXTRA_TEXT, ServerUtil.PAOWANG_URL + paowang.getContentUrl());
                                        sendIntent.setType("text/plain");
                                        startActivity(sendIntent);

                                        dialog.dismiss();
                                    }

                                    @Override
                                    public void onNegative(MaterialDialog dialog) {
                                        dialog.dismiss();
                                    }
                                })
                                .build()
                                .show();

                        break;

                    case PAPER_ARTICLE:

                        final PaperInfo paperInfo = (PaperInfo) mModelInfoAdapter.getItem(position);

                        if (TextUtils.isEmpty(paperInfo.getFromAddress())) {
                            return true;
                        }

                        new MaterialDialog.Builder(mContext)
                                .content(R.string.ifshare_content_address)
                                .positiveText(R.string.sure)
                                .negativeText(R.string.cancel)
                                .backgroundColor(mContext.getResources().getColor(R.color.white))
                                .contentColor(mContext.getResources().getColor(R.color.black))
                                .callback(new MaterialDialog.ButtonCallback() {
                                    @Override
                                    public void onPositive(MaterialDialog dialog) {

                                        Intent sendIntent = new Intent();
                                        sendIntent.setAction(Intent.ACTION_SEND);
                                        sendIntent.putExtra(Intent.EXTRA_TEXT, paperInfo.getFromAddress());
                                        sendIntent.setType("text/plain");
                                        startActivity(sendIntent);

                                        dialog.dismiss();
                                    }

                                    @Override
                                    public void onNegative(MaterialDialog dialog) {
                                        dialog.dismiss();
                                    }
                                })
                                .build()
                                .show();

                        break;
                }

                return true;
            }

        });
    }

    private void setMainListViewItemClickListener() {
        mMainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();

                switch (Project_id) {
                    case OPEN_CODE:
                        CodeInfo codeInfo = (CodeInfo) mModelInfoAdapter.getItem(position);
//                        codeInfo = DataSupport.find(CodeInfo.class, codeInfo.getId(), true);

                        bundle.putString(WebViewActivity.WEB_URL,
                                ServerUtil.PAOWANG_URL + codeInfo.getContentUrl());
                        bundle.putSerializable(WebViewActivity.OBJECT, codeInfo);
                        bundle.putInt(WebViewActivity.OBJECT_TYPE, WebViewActivity.OPEN_CODE);
                        break;

                    case PAOWANG_ARTICLE:
                        PaoWangArticle paoWangArticle = (PaoWangArticle) mModelInfoAdapter.getItem(position);
//                        paoWangArticle = DataSupport.find(PaoWangArticle.class, paoWangArticle.getId(), true);

                        bundle.putString(WebViewActivity.WEB_URL,
                                ServerUtil.PAOWANG_URL + paoWangArticle.getContentUrl());
                        bundle.putSerializable(WebViewActivity.OBJECT, paoWangArticle);
                        bundle.putInt(WebViewActivity.OBJECT_TYPE, WebViewActivity.PAOWANG);
                        break;

                    case PAPER_ARTICLE:
                        PaperInfo paperInfo = (PaperInfo) mModelInfoAdapter.getItem(position);
//                        paperInfo = DataSupport.find(PaperInfo.class, paperInfo.getId(), true);

                        bundle.putString(WebViewActivity.WEB_URL, paperInfo.getFromAddress());
                        bundle.putSerializable(WebViewActivity.OBJECT, paperInfo);
                        bundle.putInt(WebViewActivity.OBJECT_TYPE, WebViewActivity.PAPER);
                        break;

                    case MYCOLLECTION:
                        MyCollection myCollection = (MyCollection) mModelInfoAdapter.getItem(position);
//                        myCollection = DataSupport.find(MyCollection.class, myCollection.getId(), true);

                        bundle.putString(WebViewActivity.WEB_URL, myCollection.getAddressURL());
                        bundle.putSerializable(WebViewActivity.OBJECT, myCollection);
                        bundle.putInt(WebViewActivity.OBJECT_TYPE, WebViewActivity.MYCOLLECTION);
                        break;
                }
                forward(WebViewActivity.class, bundle, false);
            }
        });
    }

    private void initRefreshLayout() {
        mRefreshLayout.setLoadingMode(RefreshLayout.LoadingMode.click);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Page_index = 1;
                mRefreshLayout.setRefreshing(true);
                mRefreshLayout.setLoading(false);
                actionType = 0;

                PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
                if (!pm.isScreenOn()) {
                    wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                            PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
                    wakeLock.acquire();
                }

                executeTask();
            }
        });

        mRefreshLayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                Page_index += 1;
                actionType = 1;
                mRefreshLayout.setLoading(false);
                executeQuery();
            }
        });
    }

    private void executeTask() {
        TaskOption taskOption = new TaskOption();
        taskOption.groupIndex = Group_id;
        taskOption.pageIndex = Page_index;

        switch (Project_id) {
            case OPEN_CODE:
                taskOption.websiteUrl = ServerUtil.PAOWANG_URL + ServerUtil.PAOWANG_CODE_URL;
                mTaskManager.addCodeInfoTask(taskOption, modelInfoListener);
                break;

            case PAOWANG_ARTICLE:
                taskOption.websiteUrl = ServerUtil.PAOWANG_URL + Group_url;
                mTaskManager.addArticleTask(taskOption, modelInfoListener);

                break;

            case PAPER_ARTICLE:
                taskOption.websiteUrl = ServerUtil.PAPER_URL + Group_url;
                mTaskManager.addPaperTask(taskOption, modelInfoListener);

                break;
        }
    }

    private void initNavigationView() {
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {

                Group_id = 1;
                Page_index = 1;
                mDrawerLayout.closeDrawer(GravityCompat.START);
                mGroupAdapter.removeAll();
                mGroupAdapter.setSelectIndex(0);
                mModelInfoAdapter.removeAll();

                switch (item.getItemId()) {

                    case R.id.nav_code:
                        mToolBar.setTitle("开源代码");
                        Project_id = OPEN_CODE;

                        Group_url = Code_Group_Url;
                        mGroupAdapter.setProject(OPEN_CODE);
                        mModelInfoAdapter.setProject(OPEN_CODE);
                        mGroupAdapter.addAll(new ArrayList<>(codeInfoDataSupport));
                        break;

                    case R.id.nav_paowang:
                        mToolBar.setTitle("泡网文章");
                        Project_id = PAOWANG_ARTICLE;

                        Group_url = PaoWang_Group_Url;
                        mGroupAdapter.setProject(PAOWANG_ARTICLE);
                        mModelInfoAdapter.setProject(PAOWANG_ARTICLE);
                        mGroupAdapter.addAll(new ArrayList<>(paoWangDataSupport));

                        break;

                    case R.id.nav_paper:
                        mToolBar.setTitle("好东西日报");
                        Project_id = PAPER_ARTICLE;

                        Group_url = Paper_Group_Url;
                        mGroupAdapter.setProject(PAPER_ARTICLE);
                        mModelInfoAdapter.setProject(PAPER_ARTICLE);
                        mGroupAdapter.addAll(new ArrayList<>(paperDataSupport));

                        break;

                    case R.id.nav_mycollect:
                        mToolBar.setTitle("我的收藏");
                        Project_id = MYCOLLECTION;

                        mModelInfoAdapter.setProject(MYCOLLECTION);
                        break;
                }
                /**
                 * 这个延时，是为了让抽屉菜单先关掉
                 */
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        executeQuery();
                    }
                }, 100);

                return true;
            }
        });
    }

    private void executeQuery() {
        StateEvent stateEvent = new StateEvent();
        stateEvent.project = Project_id;
        stateEvent.group = Group_id;
        stateEvent.index = Page_index - 1;

        mQueryManager.addQuery(stateEvent, new QueryListener() {
            @Override
            public void querySuccess(StateEvent stateEvent, String successInfo) {

                List<DataSupport> dataSupportList = (List<DataSupport>) stateEvent.model;

                if (actionType == 0) {
                    mModelInfoAdapter.removeAll();
                }
                if (dataSupportList.size() <= 0) {
                    if (actionType == 1) {
                        toast("没有更多了");
                    } else {
                        toast("木有数据");
                    }
                } else {
                    mModelInfoAdapter.addAll(dataSupportList);
                }

                refreshLayout(false);
                mRefreshLayout.setLoading(false);
            }

            @Override
            public void queryFail(StateEvent stateEvent, String failInfo) {
                refreshLayout(false);
                mRefreshLayout.setLoading(false);
            }
        });

    }

    private void refreshLayout(boolean refresh) {
        mRefreshLayout.setRefreshing(refresh);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void findViews() {
        mToolBar.setTitle(R.string.app_name);
        mToolBar.setTitleTextColor(getApplicationContext().getResources().getColor(R.color.white));

        mDrawerLayout = (DrawerLayout) findViewById(R.id.main_drawer);
        mRefreshLayout = (RefreshLayout) findViewById(R.id.main_refreshlayout);
        mNavigationView = (NavigationView) findViewById(R.id.drawer_left);
        mNavigationView.setVisibility(View.GONE);
        mMainListView = (ListView) findViewById(R.id.main_listview);
        mRightListView = (ListView) findViewById(R.id.drawer_right_listView);
        floatingActionButton = (FloatingActionButton) findViewById(R.id.main_floatbutton);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMainListView.smoothScrollToPosition(0);
            }
        });
    }

    /**
     * 启用HomeButton
     */
    private void enabledHomeButton() {
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolBar, R.string.app_name, R.string.app_name) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);

            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };

        actionBarDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if (mDrawerLayout.isDrawerOpen(GravityCompat.END)) {
                mDrawerLayout.closeDrawers();
                return true;
            }

            if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                mDrawerLayout.closeDrawers();
                return true;
            }

            if (System.currentTimeMillis() - mLastBackTime > 2000) {
                toast("再按一次就退出");
                mLastBackTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(PROJECT_ID, Project_id);
        outState.putInt(GROUP_ID, Group_id);
        outState.putInt(PAGE_INDEX, Page_index);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        executeQuery();
        mModelInfoAdapter.notifyDataChangeFromQuery();
        //        refreshLayout(true);
        super.onResume();
    }

    @Override
    protected void onDestroy() {

        mRefreshLayout.setRefreshing(false);
        mGroupAdapter.removeAll();
        mModelInfoAdapter.removeAll();
        mHandler.removeCallbacksAndMessages(null);

        super.onDestroy();
    }
}
